package com.example.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.constant.MessageConstant;
import com.example.context.BaseContext;
import com.example.dto.*;
import com.example.entity.*;
import com.example.exception.AddressBookBusinessException;
import com.example.exception.OrderBusinessException;
import com.example.exception.ShoppingCartBusinessException;
import com.example.mapper.*;
import com.example.result.PageResult;
import com.example.result.Result;
import com.example.service.OrdersService;
import com.example.utils.HttpClientUtil;
import com.example.utils.RedisUtil;
import com.example.utils.WeChatPayUtil;
import com.example.vo.OrderPaymentVO;
import com.example.vo.OrderStatisticsVO;
import com.example.vo.OrderSubmitVO;
import com.example.vo.OrderVO;
import com.example.websocket.WebSocketServer;
import com.github.pagehelper.PageHelper;
import com.github.xiaoymin.knife4j.core.util.CollectionUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 订单表(Orders)表服务实现类
 *
 * @author makejava
 * @since 2024-03-12 16:46:44
 */
@Service("ordersService")
@Slf4j
public class OrdersServiceImpl implements OrdersService {
    @Resource
    private OrdersDao ordersDao;

    @Autowired
    private AddressBookDao addressBookDao;
    @Autowired
    private OrderDetailDao orderDetailDao;

    @Autowired
    private InventoryDao inventoryDao;

    @Autowired
    private ShoppingCartDao shoppingCartDao;

    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private CustomerDao customerDao;

    @Autowired
    private WebSocketServer webSocketServer;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RedisUtil redisUtil;

    @Value("${baking.shop.address}")
    private String shopAddress;

    @Value("${baking.baidu.ak}")
    private String ak;

    @Override
    @Transactional
    public Result<OrderSubmitVO> submitOrder(OrdersSubmitDTO ordersSubmitDTO) {
        //处理各种业务异常（地址簿为空，购物车为空）
        AddressBook addressBook = addressBookDao.getById(ordersSubmitDTO.getAddressBookId());
        if(addressBook==null){
            return Result.error(null,MessageConstant.ADDRESS_BOOK_IS_NULL);
//            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }

        //检查用户的收货地址是否超出配送范围
//        Result result = checkOutOfRange(addressBook.getCityName()+addressBook.getDistrictName()+addressBook.getDetail());
//        if(result.getMsg()!=null){
//            return result;
//        }
        //查询当前用户购物车数据
        Long userId = BaseContext.getCurrentId();
        ShoppingCart shoppingCart = ShoppingCart.builder()
                .id(userId)
                .storeId(ordersSubmitDTO.getStoreId())
                .build();
        List<ShoppingCart> shoppingCartList = shoppingCartDao.list(shoppingCart);
        if(shoppingCartList==null && shoppingCartList.size()==0){
            return Result.error(null,MessageConstant.SHOPPING_CART_IS_NULL);
//            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        //向订单表插入1条数据
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO,orders);
//        orders.setAddress(addressBook.getDetail());
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID);
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setPhone(addressBook.getPhone());
        orders.setConsignee(addressBook.getConsignee());
        orders.setAddress(addressBook.getDetail());
        orders.setUserId(userId);
//        orders.setUserName();
        ordersDao.insert(orders);

        //向订单明细表插入n条数据
        List<OrderDetail> orderDetails = new ArrayList<>();
        for(ShoppingCart shoppingCart1:shoppingCartList){
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(shoppingCart1,orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetail.setMethod(1);
            orderDetails.add(orderDetail);
        }
        orderDetailDao.insertBatch(orderDetails);

        //修改库存信息
        List<StoreShoppingCart> storeShoppingCarts = new ArrayList<>();
        for(ShoppingCart shoppingCart1:shoppingCartList){
            StoreShoppingCart storeShoppingCart = new StoreShoppingCart();
            BeanUtils.copyProperties(shoppingCart1,storeShoppingCart);
            storeShoppingCarts.add(storeShoppingCart);
        }

        inventoryDao.updateBatch(storeShoppingCarts);

        //将购物车数据放入Redis中，若用户未支付订单，则将库存数量改回下单前
        //构造redis中的key，order_orderNumber
        String key = "order_" + orders.getNumber();
        redisTemplate.opsForValue().set(key,shoppingCartList);

        //清空当前购物车数据
        shoppingCartDao.deleteByUserId(userId,ordersSubmitDTO.getStoreId());

        //封装vo返回结果
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .id(orders.getId())
                .orderTime(orders.getOrderTime())
                .orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount())
                .build();

        //清空缓存
        redisUtil.cleanRedis();

        return Result.success(orderSubmitVO);
    }

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public Orders queryById(Long id) {
        return this.ordersDao.queryById(id);
    }

    /**
     * 分页查询
     *
     * @param orders 筛选条件
     * @param pageRequest      分页对象
     * @return 查询结果
     */
    @Override
    public Page<Orders> queryByPage(Orders orders, PageRequest pageRequest) {
        long total = this.ordersDao.count(orders);
        return new PageImpl<>(this.ordersDao.queryAllByLimit(orders, pageRequest), pageRequest, total);
    }

    /**
     * 新增数据
     *
     * @param orders 实例对象
     * @return 实例对象
     */
    @Override
    public Orders insert(Orders orders) {
        this.ordersDao.insert(orders);
        return orders;
    }

    /**
     * 修改数据
     *
     * @param orders 实例对象
     * @return 实例对象
     */
    @Override
    public Orders update(Orders orders) {
        this.ordersDao.update(orders);
        return this.queryById(orders.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Long id) {
        return this.ordersDao.deleteById(id) > 0;
    }

    @Override
    public PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());
        com.github.pagehelper.Page<Orders> page = ordersDao.pageQuery(ordersPageQueryDTO);
        // 部分订单状态，需要额外返回订单商品信息，将Orders转化为OrderVO
        List<OrderVO> orderVOS = getOrderVOList(page);
        return new PageResult(page.getTotal(),orderVOS);
    }

    public List<OrderVO> getOrderVOList(com.github.pagehelper.Page<Orders> page){
        // 需要返回订单商品信息，自定义OrderVO响应结果
        List<OrderVO> orderVOList = new ArrayList<>();

        List<Orders> ordersList = page.getResult();
        if (!CollectionUtils.isEmpty(ordersList)) {
            for (Orders orders : ordersList) {
                // 将共同字段复制到OrderVO
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                String orderDishes = getOrderDishesStr(orders);

                // 将订单商品信息封装到orderVO中，并添加到orderVOList
                orderVO.setOrderDishes(orderDishes);
                orderVOList.add(orderVO);
            }
        }
        return orderVOList;
    }

    /**
     * 根据订单id获取商品信息字符串
     *
     * @param orders
     * @return
     */
    private String getOrderDishesStr(Orders orders) {
        // 查询订单菜品详情信息（订单中的菜品和数量）
        List<OrderDetail> orderDetailList = orderDetailDao.getByOrderId(orders.getId());

        // 将每一条订单菜品信息拼接为字符串（格式：宫保鸡丁*3；）
        List<String> orderDishList = orderDetailList.stream().map(x -> {
            String orderDish = x.getName() + "*" + x.getNumber() + ";";
            return orderDish;
        }).collect(Collectors.toList());

        // 将该订单对应的所有菜品信息拼接在一起
        return String.join("", orderDishList);
    }


    @Override
    public OrderStatisticsVO statistics() {
        Integer toBeConfirmed = ordersDao.countStatus(Orders.TO_BE_CONFIRMED);
        Integer confirmed = ordersDao.countStatus(Orders.CONFIRMED);
        Integer deliveryInProgress = ordersDao.countStatus(Orders.DELIVERY_IN_PROGRESS);
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setConfirmed(toBeConfirmed);
        orderStatisticsVO.setConfirmed(confirmed);
        orderStatisticsVO.setDeliveryInProgress(deliveryInProgress);
        return orderStatisticsVO;
    }


    @Override
    public OrderVO details(Long id) {
        Orders orders = ordersDao.getById(id);
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders,orderVO);
        List<OrderDetail> orderDetails = orderDetailDao.getByOrderId(id);
        orderVO.setOrderDetailList(orderDetails);
        return orderVO;
    }

    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        Orders orders = Orders.builder()
                .status(Orders.CONFIRMED)
                .id(ordersConfirmDTO.getId())
                .build();
        ordersDao.update(orders);
    }

    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {
        // 根据id查询订单
        Orders ordersDB = ordersDao.getById(ordersRejectionDTO.getId());

        Orders orders = Orders.builder()
                .status(7)
                .rejectionReason(ordersRejectionDTO.getRejectionReason())
                .id(ordersRejectionDTO.getId())
                .cancelTime(LocalDateTime.now())
                .build();

        //支付状态 退款
//        Integer payStatus = ordersDB.getPayStatus();
//        if (payStatus == Orders.PAID) {
//            //用户已支付，需要退款
//            String refund = weChatPayUtil.refund(
//                    ordersDB.getNumber(),
//                    ordersDB.getNumber(),
//                    new BigDecimal(0.01),
//                    new BigDecimal(0.01));
//            log.info("申请退款：{}", refund);
//        }

        ordersDao.update(orders);

    }

    @Override
    public void cancel(OrdersCancelDTO ordersCancelDTO) {
//        // 根据id查询订单
//        Orders ordersDB = orderMapper.getById(ordersCancelDTO.getId());
//
//        //支付状态
//        Integer payStatus = ordersDB.getPayStatus();
//        if (payStatus == 1) {
//            //用户已支付，需要退款
//            String refund = weChatPayUtil.refund(
//                    ordersDB.getNumber(),
//                    ordersDB.getNumber(),
//                    new BigDecimal(0.01),
//                    new BigDecimal(0.01));
//            log.info("申请退款：{}", refund);
//        }

        Orders orders = Orders.builder()
                .id(ordersCancelDTO.getId())
                .status(Orders.CANCELLED)
                .cancelReason(ordersCancelDTO.getCancelReason())
                .cancelTime(LocalDateTime.now())
                .build();
        ordersDao.update(orders);
    }

    @Override
    public Result delivery(Long id) {
        // 根据id查询订单
        Orders ordersDB = ordersDao.getById(id);

        // 校验订单是否存在，并且状态为3
        if (ordersDB == null || !ordersDB.getStatus().equals(Orders.CONFIRMED)) {
            return Result.error(MessageConstant.ORDER_STATUS_ERROR);
//            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders orders = new Orders();
        orders.setId(ordersDB.getId());
        // 更新订单状态,状态转为派送中
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);

        ordersDao.update(orders);
        return Result.success();
    }

    @Override
    public Result complete(Long id) {
        // 根据id查询订单
        Orders ordersDB = ordersDao.getById(id);

        // 校验订单是否存在，并且状态为4
        if (ordersDB == null || !ordersDB.getStatus().equals(Orders.DELIVERY_IN_PROGRESS)) {
            return Result.error(MessageConstant.ORDER_STATUS_ERROR);
//            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders orders = new Orders();
        orders.setId(ordersDB.getId());
        // 更新订单状态,状态转为完成
        orders.setStatus(Orders.COMPLETED);
        orders.setDeliveryTime(LocalDateTime.now());

        ordersDao.update(orders);
        return Result.success();
    }


    @Override
    public PageResult historyOrders(int page, int pageSize, Integer status,Long storeId) {
        PageHelper.startPage(page,pageSize);
        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        ordersPageQueryDTO.setPage(page);
        ordersPageQueryDTO.setPageSize(pageSize);
        ordersPageQueryDTO.setStatus(status);
        ordersPageQueryDTO.setStoreId(storeId);
        com.github.pagehelper.Page<Orders> pageQuery = ordersDao.pageQuery(ordersPageQueryDTO);

        List<OrderVO> orderVOS = new ArrayList<>();
        if(pageQuery.getTotal()>0&&pageQuery!=null)
            for(Orders orders:pageQuery){
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders,orderVO);
                //查询订单明细
                List<OrderDetail> orderDetails = orderDetailDao.getByOrderId(orders.getId());
                orderVO.setOrderDetailList(orderDetails);
                orderVOS.add(orderVO);
            }
        return new PageResult(pageQuery.getTotal(),orderVOS);
    }

    @Override
    public OrderVO orderDetail(Long id) {
        Orders orders = ordersDao.getById(id);
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders,orderVO);
        List<OrderDetail> orderDetails = orderDetailDao.getByOrderId(id);
        orderVO.setOrderDetailList(orderDetails);
        return orderVO;
    }

    @Override
    public Result userCancelById(Long id) {
        // 根据id查询订单
        Orders ordersDB = ordersDao.getById(id);

        // 校验订单是否存在
        if (ordersDB == null) {
            return Result.error(MessageConstant.ORDER_NOT_FOUND);
//            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        //订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
        if (ordersDB.getStatus() > 2) {
            return Result.error(MessageConstant.ORDER_STATUS_ERROR);
//            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders orders = new Orders();
        orders.setId(ordersDB.getId());

        // 订单处于待接单状态下取消，需要进行退款
        if (ordersDB.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            //调用微信支付退款接口
//            weChatPayUtil.refund(
//                    ordersDB.getNumber(), //商户订单号
//                    ordersDB.getNumber(), //商户退款单号
//                    new BigDecimal(0.01),//退款金额，单位 元
//                    new BigDecimal(0.01));//原订单金额

            //支付状态修改为 退款
            orders.setPayStatus(Orders.REFUND);
        }

        // 更新订单状态、取消原因、取消时间
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason("用户取消");
        orders.setCancelTime(LocalDateTime.now());
        ordersDao.update(orders);
        return Result.success();
    }

    @Override
    public void repetition(Long id) {
        List<OrderDetail> orderDetails = orderDetailDao.getByOrderId(id);
        Long storeId = ordersDao.getById(id).getStoreId();
        Long userId = BaseContext.getCurrentId();
        List<ShoppingCart> shoppingCartList = new ArrayList<>();
        for(OrderDetail orderDetail:orderDetails){
            ShoppingCart shoppingCart = new ShoppingCart();
            //查看库存是否还有货
            List<Inventory> inventoryList = inventoryDao.queryByProductIdAndStoreId(orderDetail.getProductId(), storeId);
            if(inventoryList.get(0).getProductNum()>=orderDetail.getNumber()){
                BeanUtils.copyProperties(orderDetail,shoppingCart);
                shoppingCart.setCreateTime(LocalDateTime.now());
                shoppingCart.setCustomerId(userId);
                shoppingCart.setStoreId(storeId);
                shoppingCartList.add(shoppingCart);
            }

        }
        shoppingCartDao.insertBatch(shoppingCartList);
    }

    /**
     * 检查客户的收货地址是否超出配送范围
     * @param address
     */
    private Result checkOutOfRange(String address) {
        Map map = new HashMap();
        map.put("address",shopAddress);
        map.put("output","json");
        map.put("ak",ak);

        //获取店铺的经纬度坐标
        String shopCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", map);

        JSONObject jsonObject = JSON.parseObject(shopCoordinate);
        if(!jsonObject.getString("status").equals("0")){
            return Result.error("店铺地址解析失败");
//            throw new OrderBusinessException("店铺地址解析失败");
        }

        //数据解析
        JSONObject location = jsonObject.getJSONObject("result").getJSONObject("location");
        String lat = location.getString("lat");
        String lng = location.getString("lng");
        //店铺经纬度坐标
        String shopLngLat = lat + "," + lng;

        map.put("address",address);
        //获取用户收货地址的经纬度坐标
        String userCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", map);

        jsonObject = JSON.parseObject(userCoordinate);
        if(!jsonObject.getString("status").equals("0")){
            return Result.error("收货地址解析失败");
//            throw new OrderBusinessException("收货地址解析失败");
        }

        //数据解析
        location = jsonObject.getJSONObject("result").getJSONObject("location");
        lat = location.getString("lat");
        lng = location.getString("lng");
        //用户收货地址经纬度坐标
        String userLngLat = lat + "," + lng;

        map.put("origin",shopLngLat);
        map.put("destination",userLngLat);
        map.put("steps_info","0");

        //路线规划
        String json = HttpClientUtil.doGet("https://api.map.baidu.com/directionlite/v1/driving", map);

        jsonObject = JSON.parseObject(json);
        if(!jsonObject.getString("status").equals("0")){
            return Result.error("配送路线规划失败");
//            throw new OrderBusinessException("配送路线规划失败");
        }

        //数据解析
        JSONObject result = jsonObject.getJSONObject("result");
        JSONArray jsonArray = (JSONArray) result.get("routes");
        Integer distance = (Integer) ((JSONObject) jsonArray.get(0)).get("distance");

        if(distance > 50000){
            //配送距离超过50000米
            return Result.error("超出配送范围");
//            throw new OrderBusinessException("超出配送范围");
        }
        return Result.success();
    }

    @Override
    public Result reminder(Long id) {
        //根据id查询订单
        Orders orders = ordersDao.getById(id);
        if(orders==null){
            return Result.error(MessageConstant.ORDER_STATUS_ERROR);
//            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Map map = new HashMap<>();
        map.put("type",2);
        map.put("orderId",id);
        map.put("content","订单号:"+orders.getNumber());
        String json = JSON.toJSONString(map);

        if(webSocketServer.getSessionMap().isEmpty()){
            //发到rabbitMQ
            String ExChangeName = "sky.direct";
            String queueName = "direct.queue";
            String routingKey = "order";
            rabbitTemplate.convertAndSend(ExChangeName,routingKey,json);
            log.info("已发送到MQ");
        }else{
            webSocketServer.sendToAllClient(json);
        }
        return Result.success();
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO)  { // throws Exception
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        Customer customer = customerDao.getById(userId);

        //调用微信支付接口，生成预支付交易单
//        JSONObject jsonObject = weChatPayUtil.pay(
//                ordersPaymentDTO.getOrderNumber(), //商户订单号
//                new BigDecimal(0.01), //支付金额，单位 元
//                "苍穹外卖订单", //商品描述
//                user.getOpenid() //微信用户的openid
//        );
//
//        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
//            throw new OrderBusinessException("该订单已支付");
//        }

//        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
//        vo.setPackageStr(jsonObject.getString("package"));
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", "ORDERPAID");
        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        BeanUtils.copyProperties(ordersPaymentDTO,vo);

        vo.setPackageStr(jsonObject.getString("package"));
        //为替代微信支付成功后的数据库订单状态更新，多定义一个方法进行修改

        paySuccess(ordersPaymentDTO.getOrderNumber());

        //删除缓存
        String key = "order_" + ordersPaymentDTO.getOrderNumber();
        redisTemplate.delete(key);

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = ordersDao.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        ordersDao.update(orders);

        //通过websocket向客户端浏览器推送消息 type orderId content
        Map map = new HashMap();
        map.put("type",1);//1表示来单提醒 2表示客户催单
        map.put("orderId",ordersDB.getId());
        map.put("content","订单号:"+ outTradeNo);


        if(webSocketServer.getSessionMap().isEmpty()){
            //发到rabbitMQ
            String ExChangeName = "baking.direct";
            String queueName = "direct.queue";
            String routingKey = "order";
            rabbitTemplate.convertAndSend(ExChangeName,routingKey,JSON.toJSONString(map));
            log.info("已发送到MQ");
        }else{
            webSocketServer.sendToAllClient(JSON.toJSONString(map));
        }

    }

    @Override
    public OrderVO orderDetailByOrderNumber(String orderNumber) {
        Orders orders = ordersDao.getByNumber(orderNumber);
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders,orderVO);
        List<OrderDetail> orderDetails = orderDetailDao.getByOrderId(orders.getId());
        orderVO.setOrderDetailList(orderDetails);
        return orderVO;
    }
}
